package java_thinking.unit_17._17_2_6;

import java.util.NoSuchElementException;

/**
 * @Desc:   没看懂，先过
 * @author: cww
 * @DateTime: 2019/4/15 20:43
 */
interface SListIterator<T> {
    boolean hasNext();
    void remove();
    void add(T element);
    T next();
}
public class SList<T> {
    private static class Link<T> {
        T element;
        Link<T> next;
        Link(T element,Link<T> next) {
            this.element = element;
            this.next = next;
        }
    }

    private final Link<T> header = new Link<T>(null,null);

    public SList() {
        header.next = header;
    }

    public SListIterator<T> iterator() {
        return new SListIteratorImpl();
    }

    public class SListIteratorImpl implements SListIterator<T> {

        private Link<T> lastReturned = header;
        private Link<T> next;

        public SListIteratorImpl() {
            next = header.next;
        }

        @Override
        public boolean hasNext() {
            return next != header;
        }

        @Override
        public void remove() {
            if (next == header) {
                throw new NoSuchElementException();
            }
            for (Link<T> curr = header;;curr = curr.next) {
                if (curr.next == lastReturned) {
                    curr.next = lastReturned.next;
                    break;
                }
                lastReturned = header;
            }
        }

        @Override
        public void add(T element) {
            lastReturned = header;
            Link<T> newLink = new Link<T>(element,next);
            //判断是否是空的list
            if (header.next == header) {
                header.next = newLink;
            } else {
                for (Link<T> curr = header;; curr = curr.next) {
                    if (curr.next == next) {
                        curr.next = newLink;
                        break;
                    }
                }
            }
        }

        @Override
        public T next() {
            if (next == header) {
                throw new NoSuchElementException();
            }
            lastReturned = next;
            next = next.next;
            return lastReturned.element;
        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("[");
        for (SListIterator<T> it = iterator();it.hasNext();){
            T element = it.next();
            builder.append(element == this ? "(this SList)" :String.valueOf(element));
            if (it.hasNext()) {
                builder.append(", ");
            }
        }
        builder.append("]");
        return builder.toString();
    }
}
